<template>
  <div style="width: auto; height: 270px" id="echarts4"></div>
</template>

<script>
import * as echarts from "echarts";
import { listEcharts4 } from "@/api/echarts/echarts";

const colors = ["#5470C6", "#EE6666"];

export default {
  name: "echarts4",
  data() {
    return {
      option: {
        title: {
          text: "异常分布图",
          textStyle: {
            color: "#FFFFFF",
          },
        },
        legend: { textStyle: { color: "#FFFFFF" } },
        tooltip: {},
        dataset: {
          dimensions: ["product", "金额异常", "项目异常", "违规异常"],
          source: [],
          textStyle: {
            color: "#FFFFFF",
          },
        },
        xAxis: { type: "category" },
        yAxis: {},
        series: [{ type: "bar" }, { type: "bar" }, { type: "bar" }],
        textStyle: {
          color: "#FFFFFF",
        },
      },
    };
  },
  mounted() {
    this.echartsInit();
    this.getList3();
  },
  methods: {
    echartsInit() {
      const chart = echarts.init(document.getElementById("echarts4"));
      chart.setOption(this.option);

      // 添加点击事件处理程序
      chart.on("click", (params) => {
        if (params.componentType === "series") {
          console.log("点击的数据点信息-----------：", params);
          this.navigateToPage(params.name, params.seriesName);
        }
      });
    },
    navigateToPage(department, exceptionType) {
      // 根据 type 和点击的数据点信息跳转到指定页面
      this.$router.push({
        path: "../orderhistory/orderHistory",
        query: { department: department, exceptionType: exceptionType },
      });
    },
    getList3() {
      this.loading = true;
      listEcharts4().then((response) => {
        const data = response;

        // 汇总数据
        const aggregatedData = {};
        data.forEach((item) => {
          if (!aggregatedData[item.department]) {
            aggregatedData[item.department] = {
              product: item.department,
              金额异常: 0,
              项目异常: 0,
              违规异常: 0,
            };
          }
          switch (item.exceptionType) {
            case 0:
              aggregatedData[item.department]["金额异常"] += item.count;
              break;
            case 1:
              aggregatedData[item.department]["项目异常"] += item.count;
              break;
            case 2:
              aggregatedData[item.department]["违规异常"] += item.count;
              break;
          }
        });

        // 将汇总数据转换为 ECharts 需要的格式
        const sourceData = Object.values(aggregatedData);

        this.option.dataset.source = sourceData;

        // 重新初始化图表
        this.echartsInit();

        this.loading = false;
      });
    },
  },
};
</script>

<style scoped></style>
